<?php
	/* -------------------------------------------------------------------
	IOU - expense sharing system 
	Copyright (C) 2009 - Mischa Spelt (m.spelt@gmail.com)
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
	
	------------------------------------------------------------------- */

	include_once "lib/lib.main.php";
	checklogin();

	print_header("Groups");

	if(isset($_POST['add'])) {
		if($db->q("value SELECT COUNT(*) FROM Users_Groups WHERE UserID = %i AND GroupID = %i", $_POST['user'], $_POST['group']) == 1)
		{
			$db->q("UPDATE Users_Groups SET IsActive = -1 WHERE UserID = %i AND GroupID = %i", $_POST['user'], $_POST['group']);
		}
		else
		{
			$db->q("INSERT INTO Users_Groups VALUES(%i, %i, -1)", $_POST['user'], $_POST['group']);
		}
	}
	if(isset($_POST['remove'])) {
		if($db->q("value SELECT COUNT(*) FROM Journal LEFT JOIN Bills ON Journal.BillID = Bills.ID WHERE Journal.UserID = %i AND Bills.GroupID = %i", $_POST['user'], $_POST['group']) == 0) {
			$db->q("DELETE FROM Users_Groups WHERE UserID = %i AND GroupID = %i", $_POST['user'], $_POST['group']);	
			print "<p class='message'>The user was removed from the group.</p>";
			if($db->q("value SELECT COUNT(*) FROM Users_Groups WHERE GroupID = %i", $_POST['group']) == 0)
			{
				$db->q("DELETE FROM Groups WHERE ID = %i", $_POST['group']);
				print "<p class='message'>No users were left in the group, so it was deleted.</p>";
			}
		} 
		elseif ($db->q("value SELECT ABS(SUM(Amount / Divisor)) FROM Journal LEFT JOIN Bills ON Journal.BillID = Bills.ID WHERE UserID = %i AND GroupID = %i", $_POST['user'], $_POST['group']) < 0.01)
		{
			$db->q("UPDATE Users_Groups SET IsActive = 0 WHERE UserID = %i AND GroupID = %i", $_POST['user'], $_POST['group']);
			print "<p class='message'>The user was removed from the group.</p>";
		}

	}
	if(isset($_POST['join'])) {
		if($db->q("value SELECT COUNT(*) FROM Users_Groups WHERE UserID = %i AND GroupID = %i", $gUser['ID'], $_POST['group']) == 1)
		{
			$db->q("UPDATE Users_Groups SET IsActive = -1 WHERE UserID = %i AND GroupID = %i", $gUser['ID'], $_POST['group']);
		}
		else
		{
			$db->q("INSERT INTO Users_Groups VALUES(%i, %i, -1)", $gUser['ID'], $_POST['group']);
		}
		$groupName = $db->q("value SELECT DisplayName FROM Groups WHERE ID = %i", $_POST['group']);
		$emails = $db->q("table SELECT DisplayName, Email FROM Users_Groups LEFT JOIN Users ON UserID = ID WHERE ID <> %i AND IsActive = -1", $gUser['ID']);
		foreach($emails as $mail) {
			mail($mail['DisplayName'] . " <" . $mail['Email'] . ">", "New user in group $groupName",
				"Dear {$mail['DisplayName']}, \n\n This is a notification to inform you that a {$gUser['DisplayName']} (username {$gUser['Login']}) has added his- or herself to the group $groupName in the IOU at " . getURL());
		}
	}
	if(isset($_POST['create'])) {
		if($db->q("value SELECT COUNT(*) FROM Groups WHERE LOWER(DisplayName) = %s", $_POST['name']) == 0)
		{
			$users = array($gUser['ID']);
			foreach(explode(",", $_POST['users']) as $user) {
				$u = $db->q("column SELECT ID FROM Users WHERE LOWER(Login) LIKE %s", trim($user) . "%");
				switch(count($u)) {
					case 0: print "<p>User {$user} not found.</p>";	break;
					case 1: array_push($users, $u[0]); break;
					default: print "<p>Multiple matches ($user), skipping. Please add the user later.</p>";
				}
			}			
			$groupID = $db->q("returnid INSERT INTO Groups(DisplayName) VALUES(%s)", $_POST['name']);
			foreach($users as $u) 
				$db->q("INSERT INTO Users_Groups(UserID, GroupID) VALUES(%i, %i)", $u, $groupID);
			print "<p>Group created.</p>";
		}
		else
			print "<p>A group by that name already exists.</p>";
	}

	array_push($takenAccessKeys, str_split("NUC"));

	print "<h1>Current groups</h1>";
	$groups = $db->q("table SELECT ID, DisplayName FROM Users_Groups LEFT JOIN Groups ON Users_Groups.GroupID = Groups.ID WHERE UserID = %i ORDER BY (ID = %i) DESC, DisplayName ASC", $gUser['ID'], $gUser['PreferredGroup']);
	print "<table class='center'>";
	if($groups) {
		$i = 0;
		foreach($groups as $group) {
			$members = $db->q("table SELECT ID, Login, DisplayName, IsActive FROM Users_Groups LEFT JOIN Users ON Users_Groups.UserID = Users.ID WHERE GroupID = %i ORDER BY IsActive = -1 DESC, DisplayName ASC", $group['ID']);
			$accessKey = assignAccessKey($group['DisplayName']);
//			$displayname = $accessKey ? preg_replace('/[' . strtoupper($accessKey) . strtolower($accessKey) . ']/', '<span class="accesskey">$0</span>', $group['DisplayName'], 1) : $group['DisplayName'];
			print "<tr" . ($i++ % 2 ? " class='gray'" : "") . " valign='top'><td><b><a href='group.php?id={$group['ID']}' title='Click for details'" . ($accessKey ? " accesskey='$accessKey'" : "") . ">" . indicateAccessKey($group['DisplayName'], $accessKey) . "</a></b></td><td><ul>";
			foreach($members as $member) 
			{
				$strike = $member['IsActive'] ? "" : " style='color: #989898; text-decoration: line-through;'";
				print "<li$strike>{$member['DisplayName']} ({$member['Login']})</li>";
			}
			print "</ul>";
			$joiners = $db->q("table SELECT ID, Login, DisplayName FROM Users WHERE ID NOT IN (SELECT UserID FROM Users_Groups WHERE GroupID = %i AND IsActive = -1)", $group['ID']);
			if(count($joiners)) {
				print "<form method='post'><input type='hidden' name='group' value='{$group['ID']}'>Add <select name='user'>";
				foreach($joiners as $j) 
					print "<option value='{$j['ID']}'>{$j['Login']} ({$j['DisplayName']})</option>";
				print "</select> to the group. <input type='submit' name='add' value='Go'></form>";
			}
			$leavers = $db->q("table SELECT Users.ID, Users.Login, Users.DisplayName, Bills.GroupID, SUM(Amount / Divisor) FROM Users LEFT JOIN Journal ON Users.ID = Journal.UserID LEFT JOIN Bills ON Journal.BillID = Bills.ID LEFT JOIN Users_Groups ON (Users_Groups.UserID = Users.ID AND Users_Groups.GroupID = Bills.GroupID) WHERE Bills.GroupID = %i AND Users_Groups.IsActive = -1 GROUP BY Users.ID, Users.Login, Users.DisplayName, Users_Groups.IsActive, Bills.GroupID HAVING ABS(SUM(Amount / Divisor)) < 0.01", $group['ID']);
			if (count($leavers)) {
				print "<form method='post'><input type='hidden' name='group' value='{$group['ID']}'>Remove <select name='user'>";
				foreach($leavers as $l) 
					print "<option value='{$l['ID']}'>{$l['Login']} ({$l['DisplayName']})</option>";
				print "</select> from the group. <input type='submit' name='remove' value='Go'></form>";
			}
		}
	}
	else 
		print "<tr><td>You are not currently in any groups. Use the options below to join an existing group or create a new one.</td></tr>";
	print "</table>";

	print "<h1>Join a group</h1>";
	print "<form method='post'>";
	print "<table>";
	print "<tr><td colspan='2'>When you join a group, the members of that group will be notified.</td></tr>";
	$groups = $db->q("column SELECT GroupID FROM Users_Groups WHERE UserID = %i", $gUser['ID']);
	$joinable = count($groups) ? $db->q("table SELECT ID, DisplayName FROM Groups WHERE ID NOT IN (%Ai) ORDER BY DisplayName", $groups) : $db->q("table SELECT ID, DisplayName FROM Groups ORDER BY DisplayName", $groups);
	if(count($joinable)) {
		print "<tr><td>Group:</td><td><select name='group' style='width: 100%;'>";
		foreach($joinable as $group) 
			print "<option value='{$group['ID']}'>{$group['DisplayName']}</option>";
		print "</select></td><td><input type='submit' name='join' value='Join group'></td></tr>";
	}
	else
		print "<tr><td><i>Currently there are no groups which you can join.</i></td></tr>";
	print "</table></form>";

	print "<h1>Create new group</h1>";
	print "<form method='post'>";
	print "<table>";
	print "<tr><td><label for='name' accesskey='N'>Group <span class='accesskey'>n</span>ame</label>:</td><td><input type='text' id='name' name='name'></td></tr>";
	print "<tr><td><label for='users' accesskey='U'>Initial <span class='accesskey'>u</span>sers</label>:</td><td>me,<input type='text' id='users' name='users'><div class='hint'>Enter multiple names (or the first parts thereof) separated by commas. Ambiguous or invalid names will be ignored, however users can be manually added later.</div></td></tr>";
	print "<tr><td colspan='2' style='text-align: center;'><input type='submit' name='create' accesskey='C' value='Create new group'></td></tr>";
	print "</table></form>";

	print_footer();
?>
